/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.insta.browser.view.frame;

import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.sexydock.tabs.DefaultTabsRemovedHandler;
import org.sexydock.tabs.Tab;
import org.sexydock.tabs.jhrome.JhromeTabbedPaneUI;

import fr.insta.browser.domain.IHistoryEntry;
import fr.insta.browser.service.history.ChangeHistoryListener;
import fr.insta.browser.service.history.IHistoryService;
import fr.insta.browser.service.tab.ITabService;
import fr.insta.browser.view.dialog.ShowSourceDialog;
import fr.insta.browser.view.menu.IJMenuBarAction;
import fr.insta.browser.view.menu.IJMenuBarWebView;
import fr.insta.browser.view.menu.JMenuBarWebView;
import fr.insta.browser.view.tab.ContentTab;
import fr.insta.browser.view.tab.ITabFactory;
import fr.insta.webview.factory.WebObjectFactory;
import fr.insta.webview.object.IWebObject;
import fr.insta.webview.service.ServiceWebObject;

/**
 * <p>MainFrame class.</p>
 *
 * @author Maarek
 * @version $Id: $Id
 */
public class MainFrame extends javax.swing.JFrame implements IJMenuBarAction {

    private JTabbedPane tabbedPane;
    final private ITabFactory tabFactory;
    final private ITabService tabService;
    final private IHistoryService historyService;
    
    private final JMenuBarWebView jMenuBarWebView;
    
    private int historyState = HISTORY_PUBLIC;
    
    public static final int HISTORY_PUBLIC = 0;
    public static final int HISTORY_PRIVATE = 1;
    
    /**
     * <p>Constructor for MainFrame.</p>
     *
     * @param tabFactory a {@link fr.insta.browser.view.tab.ITabFactory} object.
     * @param tabService a {@link fr.insta.browser.service.tab.ITabService} object.
     * @param historyService a {@link fr.insta.browser.service.history.IHistoryService} object.
     */
    public MainFrame(ITabFactory tabFactory, ITabService tabService, IHistoryService historyService) {
        super();
        this.tabFactory = tabFactory;
        this.tabService = tabService;
        this.historyService = historyService;
        
        jMenuBarWebView = new JMenuBarWebView(this);
    }

    /**
     * <p>init.</p>
     */
    public void init() {
        initComponents();
        connectListeners();
        tabFactory.setTabbedPane(tabbedPane);

        Tab tab = tabFactory.createTabWithContent();
        tabbedPane.addTab(tab.getTitle(), tab.getContent());
        
        KeyboardFocusManager.getCurrentKeyboardFocusManager()
        	.addKeyEventDispatcher(new KeyEventDispatcher() {

			@Override
			public boolean dispatchKeyEvent(KeyEvent _arg0)
			{
				if(_arg0.getID() == 402) {
					if(_arg0.getKeyCode() == KeyEvent.VK_F5) {
						((ContentTab) tabService.getCurrentTab()).onClickRefresh();
						return true;
					}
				}
				return false;
			}
        });
    }

    private void initComponents() {
        tabbedPane = new JTabbedPane();
        tabbedPane.setUI(new JhromeTabbedPaneUI());
        tabbedPane.putClientProperty(JhromeTabbedPaneUI.TAB_CLOSE_BUTTONS_VISIBLE, true);
        tabbedPane.putClientProperty(JhromeTabbedPaneUI.NEW_TAB_BUTTON_VISIBLE, true);
        tabbedPane.putClientProperty(JhromeTabbedPaneUI.TAB_FACTORY, tabFactory);
        tabbedPane.addContainerListener(new DefaultTabsRemovedHandler());

        getContentPane().add(tabbedPane);
        
        this.setJMenuBar(jMenuBarWebView);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        setPreferredSize(new Dimension(1024, 600));
    }

    private void connectListeners() {
        tabbedPane.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                tabService.setCurrentTab(tabbedPane.getSelectedComponent());
            }
        });
        
        historyService.addListener(new ChangeHistoryListener()
		{
			@Override
			public void onChangeCurrentEntry(IHistoryEntry _entry)
			{		
			}
			
			@Override
			public void onAddEntry(IHistoryEntry _entry)
			{
				if(historyState == HISTORY_PUBLIC){
					ServiceWebObject.INSTANCE.serializeHistory(_entry);
					jMenuBarWebView.getListHistory().add(_entry);
					jMenuBarWebView.refreshHistory();
				}
			}
		});
    }

    /** {@inheritDoc} */
    @Override
    public void onClickGotoWebObject(IWebObject _webObject) {
    	((ContentTab) tabService.getCurrentTab()).getWebView().loadURL(_webObject.getUrl());
    }

    /** {@inheritDoc} */
    @Override
    public void onClickShowHistory() {
		WebObjectFrame webObjectFrame = new WebObjectFrame(jMenuBarWebView, jMenuBarWebView.getListHistory());
		webObjectFrame.setTitle("Vue des historiques");
		webObjectFrame.setFileInfo("History/", ".history");
    }

    /** {@inheritDoc} */
    @Override
    public void onClickAddBookmark() {
        String url = ((ContentTab) tabService.getCurrentTab()).getCurrentUrl();
        String title = ((ContentTab) tabService.getCurrentTab()).getCurrentTitle();
        
        IWebObject webObject = WebObjectFactory.getBookmarkFactory().createNewWebObject(title, url);
        ServiceWebObject.INSTANCE.serializeBookmark(webObject);
        
        jMenuBarWebView.getListBookmark().add(webObject);
        jMenuBarWebView.refreshBookmark();
        
        JOptionPane.showMessageDialog(null, "Marque page ajouté");
    }

    /** {@inheritDoc} */
    @Override
    public void onClickZoomIn() {
        ContentTab tab = (ContentTab) tabService.getCurrentTab();
        tab.getWebView().zoomIn();
    }

    /** {@inheritDoc} */
    @Override
    public void onClickZoomOut() {
        ContentTab tab = (ContentTab) tabService.getCurrentTab();
        tab.getWebView().zoomOut();
    }

    /** {@inheritDoc} */
    @Override
    public void onClickShowSource() {
        ContentTab tab = (ContentTab) tabService.getCurrentTab();
        ShowSourceDialog dialog = new ShowSourceDialog(this, false);
        dialog.setSource(tab.getWebView().getSource());
        dialog.setVisible(true);
    }

	/** {@inheritDoc} */
	@Override
	public void onClickShowBookmark()
	{
		WebObjectFrame webObjectFrame = new WebObjectFrame(jMenuBarWebView, jMenuBarWebView.getListBookmark());
		webObjectFrame.setTitle("Vue des marques pages");
		webObjectFrame.setFileInfo("Bookmark/", ".bookmark");
	}

	/** {@inheritDoc} */
	@Override
	public void onClickShowPrefs()
	{
		new ToolsFrame(this);
	}
	
	public IJMenuBarWebView getJMenuBarWebView() {
		return jMenuBarWebView;
	}
	
	public int getHistoryState() {
		return historyState;
	}
	
	public void changeHistoryState() {
		historyState = historyState == HISTORY_PRIVATE ? HISTORY_PUBLIC : HISTORY_PRIVATE;
	}

	public ITabService getTabService() {
		return tabService;
	}

	
}
